package com.video.controller.system;

import com.qf.entity.ResultData;
import com.video.netty.commons.utils.ChannelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 设置golang服务器的ip
 */
@Controller
@RequestMapping("/golang")
public class GolangController {

    @Value("${golang.host}")
    private String golangHost;

    @Value("${golang.port}")
    private String golangPort;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ChannelUtil channelUtil;

    /**
     * 设置ip
     * @return
     */
    @RequestMapping("/ip")
    public String ip(Model model){

        //获取ip地址
        String redisGolangHost = redisTemplate.opsForValue().get("golangHost");
        if (redisGolangHost == null){
            redisGolangHost = golangHost;
            //更新到redis中
            redisTemplate.opsForValue().set("golangHost", redisGolangHost);
        }

        //获取端口地址
        String redisGolangPort = redisTemplate.opsForValue().get("golangPort");
        if (redisGolangPort == null){
            redisGolangPort = golangPort;
            //更新到redis中
            redisTemplate.opsForValue().set("golangPort", redisGolangPort);
        }

        model.addAttribute("golangPort", redisGolangPort);
        model.addAttribute("golangHost", redisGolangHost);

        return "system/golangip";
    }

    /**
     * 修改GolangIp地址
     * @return
     */
    @RequestMapping("/updateip")
    @ResponseBody
    public ResultData updateIp(String ip, String port){

        if (ip != null && port != null) {
            //更新到redis中
            redisTemplate.opsForValue().set("golangHost", ip);
            redisTemplate.opsForValue().set("golangPort", port);

            //重新连接Golang服务器
            channelUtil.close();

            return new ResultData().setCode(ResultData.ResultCodeList.OK);
        }

        return new ResultData().setCode(ResultData.ResultCodeList.ERROR).setMsg("ip地址异常，修改失败！");
    }

    /**
     * 查看golang服务器的连接状态
     * @return
     */
    @ResponseBody
    @RequestMapping("/status")
    public ResultData<Boolean> status(){
        return new ResultData<Boolean>().setCode(ResultData.ResultCodeList.OK)
                .setData(channelUtil.isConnection());
    }
}
